package cn.edu.szpt.qqdemov3.net;

import android.os.AsyncTask;
import android.os.Build;
import android.util.Log;

import androidx.annotation.RequiresApi;

import com.google.gson.Gson;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.Writer;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.Buffer;

public class MyHttpUrlConnection  extends AsyncTask<Object, Integer, String> {

    private String url;
    private BufferedReader bufferedReader;
    private HttpURLConnection urlConnection;
    private String method;
    private StringBuilder stringBuffer;


    @Override
    protected String doInBackground(Object... objects) {



        try {

            Log.d("TAG", "run: " + Thread.currentThread());

            urlConnection = (HttpURLConnection) new URL(url).openConnection();


            urlConnection.setRequestMethod(method);

            urlConnection.setConnectTimeout(3000);
            urlConnection.setRequestProperty("Content-Type", "application/json");
//            urlConnection.setRequestProperty("charter", "utf-8");
            urlConnection.connect();

            int responseCode = urlConnection.getResponseCode();

            if (responseCode == 200) {
                stringBuffer = new StringBuilder();
                bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));

                String line;
                if (null != (line = bufferedReader.readLine())) {
                    stringBuffer.append(line);
                }




            }


        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            DoCloseUtil.close(bufferedReader);


            if (urlConnection != null) {
                urlConnection.disconnect();
            }


        }


        return stringBuffer.toString();
    }

    public void doGet(String url) {


        this.url = url;
        this.method = "GET";
        execute();


    }

    public void doPost() {
        this.method = "POST";
        execute();
    }



}
